<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@ include file="/jsp/common/common.jsp" %>

<script src="<%=basePath%>/static/js/GooFlow.js"></script>
<script src="<%=basePath%>/static/js/jquery.ztree.all-3.5.min.js"></script>
<link href="<%=basePath%>/static/css/metroStyle.css" rel="stylesheet" type="text/css">
<link href="<%=basePath%>/static/css/GooFlow2.css" rel="stylesheet" type="text/css">

</head>
<body>

<div class="documentContent"  id="documentContent">
	<div class="top-div"><em></em><span>&nbsp;>&nbsp;流程管理&nbsp;>&nbsp;流程定义设计</span></div>
	<div>
		<div class="wf-content-left">
			<div style="margin: 5px;">
				域：
				<select id="domain" class="table-input">
					<option value="">请选择</option>
				</select>
			</div>
			<div style="margin: 5px;">
				<button class="btn-table" id="addTypeButton">新建类型</button>
				<button class="btn-table" id="addProcessButton">新建流程</button>
			</div>
			<div style="margin: 5px;">
				<button class="btn-table" id="addVersionButton">新建版本</button>
				<button class="btn-table" id="setEffectiveButton">设为有效</button>
			</div>
			<ul id="ztreeUl" class="ztree"></ul>
		</div>
		<div class="wf-content-center" id="demo"></div>
		<div class="wf-content-right">
		
		<!-- form-box -->
		<div class="form-box">
			<h2 class="form-title">基本信息</h2>
			<div class="form-content">
			 	<table width="100%" border="0" cellpadding="0" cellspacing="0" class="form-table" id="activityTable" style="display: none;">
			 		<tr>
			 			<td class="form-table-tdleft" width="20%">名称</td>
			 			<td width="80%"><input name="actName" value="" /></td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">编号</td>
			 			<td><input name="actNo" value="" /></td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">类型</td>
			 			<td><span name="type"></span></td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">激活</td>
			 			<td>
				 			<select name="activeType" class="table-input">
				 				<option value="all">所有前面路径激活本环节激活</option>
				 				<option value="one">任意前面路径激活本环节激活</option>
				 			</select>
			 			</td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">处理</td>
			 			<td>
			 				<div style="height: 40px;">
			 					<input type="radio" name="excuteType" value="org" /> 机构 &nbsp;
			 					<span name="orgName"></span>&nbsp;
			 					<input type="hidden" name="orgId" value="" />
									<button class="btn-table" name="selectOrgButton">选择机构</button>
			 				</div>
			 				<div style="height: 40px;">
			 					<input type="radio" name="excuteType" value="group" /> 静态群组 &nbsp;
			 					<span name="groupName"></span>&nbsp;
			 					<input type="hidden" name="groupId" value="" />
									<button class="btn-table" name="selectStaticGroupButton">选择群组</button>
			 				</div>
			 				<div style="height: 40px;">
			 					<input type="radio" name="excuteType" value="ei" /> 所有群组 &nbsp;
			 					<span name="memberGroupName"></span>&nbsp;
			 					<input type="hidden" name="memberGroupId" value="" />
									<button class="btn-table" name="selectAllGroupButton">选择群组</button>
			 				</div>
			 				<div style="height: 40px;">
			 					<input type="radio" name="excuteType" value="other" />其他环节处理人 &nbsp;
			 					<select name="otherActId" class="table-input" style="width: 50%;"></select>
			 				</div>
			 			</td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">函数</td>
			 			<td><textarea cols="35" rows="4" name="customFunction"></textarea></td>
			 		</tr>
			 	</table>
			 	
			 	<table width="100%" border="0" cellpadding="0" cellspacing="0" class="form-table" id="pathTable" style="display: none;">
			 		<tr>
			 			<td class="form-table-tdleft" width="30%">名称</td>
			 			<td width="70%"><input name="pathName" value="" /></td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">编号</td>
			 			<td><input name="pathNo" value="" /></td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">类型</td>
			 			<td>
			 				<select name="pathType">
				 				<option value="normal">普通</option>
				 				<option value="back">退回</option>
				 			</select>
			 			</td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">处理类型</td>
			 			<td>
				 			<select name="multiType">
				 				<option value="single">单人处理</option>
				 				<option value="compete">抢先处理</option>
				 				<option value="serial">分组串行</option>
				 				<option value="parallel">分组并行</option>
				 			</select>
			 			</td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">等待环节</td>
			 			<td name="waitCheckTd"></td>
			 		</tr>
			 	</table>
			 	
			 	<table width="100%" border="0" cellpadding="0" cellspacing="0" class="form-table" id="routeTable" style="display: none;">
			 		<tr>
			 			<td class="form-table-tdleft" width="30%">名称</td>
			 			<td width="70%"><input name="routeName" value="" /></td>
			 		</tr>
			 		<tr>
			 			<td class="form-table-tdleft">类型</td>
			 			<td>路由</td>
			 		</tr>
			 	</table>
			 	<button class="btn-table" id="saveNodeButton">保存</button>
			 	<textarea cols="35" rows="8" id="debug"></textarea>
			</div>
		</div>
		<!-- form-box -->
		
		</div>
	</div>
</div>

<div style="display: none;">
	<input name="resourceId" id="resourceId" value="" />
	<input name="nodeId" id="nodeId" value="" />
	<input name="model" id="model" value="" />
	
</div>

<script type="text/javascript">

/**
 * 全局变量
 */
var zTreeGobalObjcet;

var gooFlowGobalObject;

var nodeInfoInstance;


$(document).ready(function(){
	
	initGooFlow();
	
	blindButton();
	
	getPageData();
	
});

/****************************************************
 * GooFlow
 ****************************************************/
 
var property={
	width:700,
	height:document.documentElement.clientHeight - 40,
	toolBtns:["start round","end round","task","fork"],
	//toolBtns:["task","node","chat","state","plug"],
	haveHead:true,
	headBtns:["save","undo","redo"],//如果haveHead=true，则定义HEAD区的按钮
	haveTool:true,
	useOperStack:true
};

var remark={
	cursor:"选择指针",
	direct:"转换连线",
	start:"开始结点",
	end:"结束结点",
	task:"任务结点",
	node:"自动结点",
	chat:"决策结点",
	state:"状态结点",
	plug:"附加插件",
	fork:"分支结点",
	join:"联合结点",
	complex:"复合结点",
	group:"组织划分框编辑开关"
};
 
/**
 * 初始化GooFlow对象
 */
function initGooFlow(){
	
		gooFlowGobalObject=$.createGooFlow($("#demo"),property);
		gooFlowGobalObject.setNodeRemarks(remark);
/* 		gooFlowGobalObject.onItemDel=function(id,type){
			return confirm("确定要删除该单元吗?");
		} */
		
	   /**
		* 元素获得焦点时候的回调函数
		*/
		gooFlowGobalObject.onItemFocus=function(id,model){
			nodeInfoInstance.showInfo(id, model);
		    return true;
		};
		
	   /**
		* 元素失去焦点时候的回调函数
		*/
		gooFlowGobalObject.onItemBlur = function(){
		     nodeInfoInstance.clearInfo();
		     return true;
		}
		
		gooFlowGobalObject.onBtnSaveClick = function(){
			saveFlowData();
		}
		
		gooFlowGobalObject.onItemAdd = function(id,type,json){
			var numArray = id.split('_');
			var num = numArray[numArray.length-1];
			if(type === 'node'){
				if(json.data){
					if(!json.data.actNo || json.data.actNo === ''){
						json.data.actNo = 'act'+num;
					}
				}else{
					json.data = {
						actNo: 'act'+num
					};
				}
				
				//gooFlowGobalObject.$nodeData[id] = json;
				
			}else if(type === 'line'){
				if(json.data){
					if(!json.data.pathNo || json.data.pathNo === ''){
						json.data.pathNo = 'pth'+num;
					}
				}else{
					json.data = {
							pathNo: 'pth'+num
					};
				}
				
				//gooFlowGobalObject.$lineData[id] = json;
			}
			
			return true;
		}
}

/**
 * 保存流程数据
 */
function saveFlowData(){
	var flowData = gooFlowGobalObject.exportData();
	var flowDataStr = JSON.stringify(flowData);
	$('#debug').val(flowDataStr);
	
	var nodes = zTreeGobalObjcet.getCheckedNodes(true);
	var verNode = nodes[0];
	var defNode = verNode.getParentNode();
	
	var version = verNode.version;
	var processDefinitionId = defNode.extendData.processDefinitionId;
	
 	var url = '<%=basePath%>/biz/workflow/processDefinition/saveProcessDefinition.do?version='+version;
 	url = url + '&processDefinitionId='+processDefinitionId;
 	url = url + '&resourceId='+$('#resourceId').val();
 	
	$.ajax({  
        url:url,  
        type:'post',  
        dataType:'json',  
        data:{flowData:JSON.stringify(flowData)},
        success:function(data,textStatus,jqXHR){  
        	showAlert('保存成功');
        },  
        error:function(XMLHttpRequest,textStatus,errorThrown){  
        	showAlert('保存失败');
        }                     
    });
}

/****************************************************
 * GooFlow
 ****************************************************/

/*****************************************************
 * zTree
 ****************************************************/
function initzTree(domainId){
	
	var zTreeUrl = '<%=basePath%>/biz/workflow/processDefinition/getBodefTreeData.do?domainId='+domainId;
	var setting = {
			check: {
				enable: true
			},
			async:{
				enable:true,
				type:'post',
				url: zTreeUrl
			},
    		view: {
    			dblClickExpand: false,
    			showLine: true,
    			selectedMulti: true,
    			showIcon:true
    		},
    		data: {
    			simpleData: {
    				enable:true,
    				idKey: "id",
    				pIdKey: "pId",
    				rootPId: "-1"
    			}
    		},
    		check: {
    			enable: true,
    			chkStyle: 'radio',
    			radioType:'all'
    		},

    		callback: {
    			onClick: zTreeOnClick,
    			onCheck: zTreeOnCheck
    		}
    	};
    
	zTreeGobalObjcet = $.fn.zTree.init($('#ztreeUl'), setting, null);
}

function zTreeOnClick(event, treeId, treeNode){
	//alert(treeNode.tId + ", " + treeNode.name);
}

function zTreeOnCheck(event, treeId, treeNode){
	if(treeNode.resourceId){
		$('#resourceId').val(treeNode.resourceId);
		
	 	var url = '<%=basePath%>/biz/workflow/processDefinition/getProcessResource.do?resourceId='+treeNode.resourceId;
	 	
		$.ajax({  
	        url:url,  
	        type:'post',  
	        dataType:'json',  
	        success:function(data,textStatus,jqXHR){  
	        	var jsondata = JSON.parse(data);
	        	gooFlowGobalObject.clearData();
	        	gooFlowGobalObject.loadData(jsondata);
	        	$('#debug').val(data);
	        },  
	        error:function(XMLHttpRequest,textStatus,errorThrown){  
	        	
	        }                     
	    });
		
	}else{
		$('#resourceId').val('');
	}
}
/*****************************************************
 * zTree
 ****************************************************/
function blindButton(){
	
	$('#addProcessDefinitionButton').on('click',function(){
		var nodes = zTreeGobalObjcet.getCheckedNodes(true);
	});
	
	$('#saveNodeButton').on('click',function(){
		nodeInfoInstance.saveNode();
	});
	
	$('#domain').on('change',function(){
		if($(this).val() != ''){
			initzTree($(this).val());
		}else{
			$.fn.zTree.destroy();
			gooFlowGobalObject.clearData();
			nodeInfoInstance.clearInfo();
		}
	});
}

function getPageData(){
	
 	var url = '<%=basePath%>/biz/domain/getAllDomain.do';
 	
	$.ajax({  
        url:url,  
        type:'post',  
        dataType:'json',  
        success:function(data,textStatus,jqXHR){  
        	$(data).each(function(index,entry){
        		var optionObj = $('<option></option>').append(entry.name).attr('value',entry.id);
        		$('#domain').append(optionObj);
        	});
        	
        },  
        error:function(XMLHttpRequest,textStatus,errorThrown){  
        }                     
    });
	
}

/********************************************************************************
 * 
 * NodeInfo
 *
 ********************************************************************************/
 

 
var NodeInfoObject = function(){
	this.activityTable = $('#activityTable');
	this.pathTable = $('#pathTable');
	this.routeTable = $('#routeTable');
	this.activityStr = "node";
	this.pathStr = "line";
	this.nodeTask = 'task';
	this.nodeFork = 'fork';
	this.nodeIdInput = $('#nodeId');
	this.nodeModelInput = $('#model');
	this.saveButton = $('#saveNodeButton');
	this._init();
}

NodeInfoObject.prototype = {
		
	getDicValue : function(key){
		
		switch (key) {
		case 'start round':
			return '开始';
			break;
		case 'end round':
			return '结束';
			break;
		case 'task':
			return '环节';
			break;
		case 'fork':
			return '路由';
			break;
		default:
			return '';
			break;
		}
		
	},
	
	getDefaultValue : function(val,defaultValue){
		if(val){
			return val;
		}else if(defaultValue){
			return defaultValue;
		}else{
			return '';
		}
	},
		
	getNodeObj : function(id,model){
		
		var result;
		
		if(model === this.activityStr){//环节信息
			result = gooFlowGobalObject.$nodeData[id];
		}else if(model === this.pathStr){//路径信息
			result = gooFlowGobalObject.$lineData[id];
		}
		
		return result;
	},	
	
	_init : function(){
		this.blindElementActivity();
		this.blindElementPath();
	},
	
	_creatNodeSelect : function(){
		
		var _this = this;
		
		var selectObject = $(this.activityTable).find('select[name="otherActId"]');
		$(selectObject).empty();
		var optionObject0 = $('<option>请选择</option>').attr('value','');
		$(selectObject).append(optionObject0);
		$.each(gooFlowGobalObject.$nodeData,function(key,value){
			if(value.type === _this.nodeTask){
				var optionObject = $('<option>'+value.name+'</option>').attr('value',key);
				$(selectObject).append(optionObject);
			}
		});
	},
	
	_creatNodeCheckbox : function(checkArray){
		var tdObj = $(this.pathTable).find('td[name="waitCheckTd"]');
		$(tdObj).empty();
		var _this = this;
		$.each(gooFlowGobalObject.$nodeData,function(key,value){
			if(value.type === _this.nodeTask){
				var divObj = $('<div><input type="checkbox" name="waitAct" value="' + key + '" />' + value.name + '</div>');
				if(_this._isInList(key,checkArray)){
					$(divObj).find('input').attr('checked','checked');
				}
				$(tdObj).append(divObj);
			}
		});
	},
	
	_isInList : function(key,array){
		
		if(!array){
			return false;
		}
		
		var result = false;
		
		$(array).each(function(index,entry){
			if(key === entry){
				result = true;
				return false;
			}
		});
		
		return result;
	},
		
	showInfo : function(id,model){
		
		$(this.nodeIdInput).val(id);
		$(this.nodeModelInput).val(model);
		
		var nodeObj = this.getNodeObj(id, model);
		var nodeData = nodeObj.data;
		
		
		
		if(model === this.activityStr){//环节信息
			
			if(nodeObj.type === this.nodeTask){
				this._creatNodeSelect();
				$(this.activityTable).show();
				$(this.pathTable).hide();
				$(this.routeTable).hide();
			}else if(nodeObj.type === this.nodeFork){
				$(this.routeTable).show();
				$(this.activityTable).hide();
				$(this.pathTable).hide();
			}
			
		}else if(model === this.pathStr){//路径信息
			$(this.activityTable).hide();
			$(this.pathTable).show();
		}
		
		$(this.saveButton).show();
		this.setValue(id, model, nodeObj);
	},
	
	blindElementPath : function(){
		
	},
	
	getExcuteTypeObj : function(){
		return $(this.activityTable).find('input:radio[name="excuteType"]:checked');
	},
	
	blindElementActivity : function(){
		var _this = this;
		
		//选择部门
		$(this.activityTable).find('button[name="selectOrgButton"]').on('click',function(){
			var excuteTypeObj = _this.getExcuteTypeObj();
			if($(excuteTypeObj).val() !== 'org'){
				return;
			}
			
			organizationSelectTree('<%=basePath%>', $('#domain').val(), function(pageData,layer){
				$(this.activityTable).find('input[name="orgId"]').val(pageData[0].id);
				$(this.activityTable).find('span[name="orgName"]').html(pageData[0].name);
				layer.close();
			});
		});
		
		//选择群组
		$(this.activityTable).find('button[name="selectStaticGroupButton"]').on('click',function(){
			var excuteTypeObj = _this.getExcuteTypeObj();
			if($(excuteTypeObj).val() !== 'group'){
				return;
			}
			
			groupSelectTree('<%=basePath%>', $('#domain').val(), function(pageData,layer){
				$(this.activityTable).find('input[name="groupId"]').val(pageData[0].id);
				$(this.activityTable).find('span[name="groupName"]').html(pageData[0].name);
				layer.close();
			});
		});
		
		//选择群组下的身份
		$(this.activityTable).find('button[name="selectAllGroupButton"]').on('click',function(){
			var excuteTypeObj = _this.getExcuteTypeObj();
			
			if($(excuteTypeObj).val() !== 'ei'){
				return;
			}
			
			groupSelectTree('<%=basePath%>', $('#domain').val(), function(pageData,layer){
				$(this.activityTable).find('input[name="memberGroupId"]').val(pageData[0].id);
				$(this.activityTable).find('span[name="memberGroupName"]').html(pageData[0].name);
				layer.close();
			});
		});
		

		
	},
	
	setValue : function(id,model,nodeObj){
		
		var nodeData = nodeObj.data || {};
		
		if(model === this.activityStr){//环节信息
			$(this.activityTable).find('input[name="actName"]').val(this.getDefaultValue(nodeData.actName));
			$(this.activityTable).find('input[name="actNo"]').val(this.getDefaultValue(nodeData.actNo));
			$(this.activityTable).find('span[name="type"]').html(this.getDicValue(nodeObj.type));
			$(this.activityTable).find('select[name="activeType"]').val(this.getDefaultValue(nodeData.activeType));
			
			$(this.activityTable).find('input[name="excuteType"]').each(function(index,element){
				if($(element).attr('value') === nodeData.excuteType){
					$(element).attr('checked','checked');
				}else{
					$(element).removeAttr('checked');
				}
			});
			
			$(this.activityTable).find('input[name="orgId"]').val(this.getDefaultValue(nodeData.orgId));
			$(this.activityTable).find('span[name="orgName"]').html(this.getDefaultValue(nodeData.orgName));
			
			$(this.activityTable).find('input[name="groupId"]').val(this.getDefaultValue(nodeData.groupId));
			$(this.activityTable).find('span[name="groupName"]').html(this.getDefaultValue(nodeData.groupName));
			
			$(this.activityTable).find('input[name="memberGroupId"]').val(this.getDefaultValue(nodeData.memberGroupId));
			$(this.activityTable).find('span[name="memberGroupName"]').html(this.getDefaultValue(nodeData.memberGroupName));
			
			$(this.activityTable).find('select[name="otherActId"]').val(this.getDefaultValue(nodeData.otherActId));
			
		}else if(model === this.pathStr){//路径信息
			
			$(this.pathTable).find('input[name="pathNo"]').val(this.getDefaultValue(nodeData.pathNo));
			$(this.pathTable).find('input[name="pathName"]').val(this.getDefaultValue(nodeData.pathName));
			$(this.pathTable).find('select[name="pathType"]').val(this.getDefaultValue(nodeData.pathType));
			$(this.pathTable).find('select[name="multiType"]').val(this.getDefaultValue(nodeData.multiType));
			
			this._creatNodeCheckbox(nodeData.waitAct);

		}
	},
	
	clearInfo : function(){
		$(this.activityTable).hide();
		$(this.pathTable).hide();
		$(this.routeTable).hide();
		$(this.saveButton).hide();
		
		
	},
	
	saveNode : function(){
		
		var data = this.packageData();
		var model = $(this.nodeModelInput).val();
		var id = $(this.nodeIdInput).val();
		
		if(id === ''){
			return;
		}
		
		if(model === this.pathStr){
			object = gooFlowGobalObject.$lineData[id];
			object.data = data;
			gooFlowGobalObject.$lineData[id] = object;
			
		}else if(model === this.activityStr){
			object = gooFlowGobalObject.$nodeData[id];
			object.data = data;
			
			var displayName;
			if(object.type === this.nodeFork){
				displayName = data.routeName;
			}else{
				displayName = data.actName + '[' + data.actNo + ']';
			}
			gooFlowGobalObject.setName(id,displayName,this.activityStr);
			gooFlowGobalObject.$nodeData[id] = object;
		}
		
		
	},
	
	packageData : function(){
		var model = $(this.nodeModelInput).val();
		var id = $(this.nodeIdInput).val();
		
		var dataObject;
		if(model === this.pathStr){//路径
			var waitAct = [];
			$(this.pathTable).find('input[name="waitAct"]').each(function(index,element){
				if($(element).attr('checked') === 'checked'){
					waitAct.push($(element).val());
				}
			});
			
			dataObject = {
				pathNo : this.getDefaultValue($(this.pathTable).find('input[name="pathNo"]').val()),
				pathName : this.getDefaultValue($(this.pathTable).find('input[name="pathName"]').val()),
				pathType : this.getDefaultValue($(this.pathTable).find('select[name="pathType"]').val()),
				multiType : this.getDefaultValue($(this.pathTable).find('select[name="multiType"]').val()),
				waitAct : waitAct
			};
		}else if(model === this.activityStr){//环节
			var nodeObject = gooFlowGobalObject.$nodeData[id];
			if(nodeObject.type === this.nodeFork){
				dataObject = {
					routeName : this.getDefaultValue($(this.activityTable).find('input[name="routeName"]').val())
				};
			}else{
				dataObject = {
					actName : this.getDefaultValue($(this.activityTable).find('input[name="actName"]').val()),
					actNo : this.getDefaultValue($(this.activityTable).find('input[name="actNo"]').val()),
					activeType : this.getDefaultValue($(this.activityTable).find('select[name="activeType"]').val()),
					excuteType : this.getDefaultValue(this.getExcuteTypeObj().attr('value')),
					orgId : this.getDefaultValue($(this.activityTable).find('input[name="orgId"]').val()),
					orgName : this.getDefaultValue($(this.activityTable).find('span[name="orgName"]').html()),
					groupId : this.getDefaultValue($(this.activityTable).find('input[name="groupId"]').val()),
					groupName : this.getDefaultValue($(this.activityTable).find('span[name="groupName"]').html()),
					memberGroupId : this.getDefaultValue($(this.activityTable).find('input[name="memberGroupId"]').val()),
					memberGroupName : this.getDefaultValue($(this.activityTable).find('span[name="memberGroupName"]').html()),
					otherActId : this.getDefaultValue($(this.activityTable).find('select[name="otherActId"]').val())
				};
			}
			
			
		}
		
		return dataObject;
	}
}

nodeInfoInstance = new NodeInfoObject();
/********************************************************************************
 * 
 * NodeInfo
 *
 ********************************************************************************/

</script>
</body>
</html>